<?php
/********************************************************************
 *	Author:
 *		Jestery Liu <jestery@gmail.com>
 *		http://www.pte.cn
 *
 *	File:			Config.class.php
 *	Create Date:	2005-10-12 15:13:08 CST
 *******************************************************************/


/**
 * 配置文件读写
 * 目前只支持 string
 * 
 * @author Jestery <jestery@gmail.com>
 * 
 * 例子：
 * 
 * 配置文件 config.inc.php:
 * <code>
 * <?php
 * // This is a config file.
 * #BEGIN#
 * $conf['database_host'] = 'localhost';
 * $conf['database_user'] = 'root';
 * $conf['database_passwd'] = 'abcde';
 * #END#
 * ?>
 * </code>
 * 读写：
 * <code>
 * $config = new Config('./config.inc.php');
 * $dbhost = $config->get('database_host');
 * $config->set('database_passwd', '123');
 * $config->save();
 * </code>
 *
 */
class Config
{
	private $conf_var_name;
	private $conf_file;
	private $conf;
	private $begin_limiter;
	private $end_limter;

	public function __construct($conf_file=null, $conf_var_name = 'conf')
	{
		$this->conf_var_name = $conf_var_name;
		$this->conf_file = $conf_file;
		$this->begin_limiter = '#BEGIN#';
		$this->end_limter = '#END#';
		if (!is_null($conf_file))
			$this->load();
	}

	public function get($name)
	{
		return $this->conf[$name];
	}

	public function getAllSettings()
	{
		return $this->conf;
	}

	public function set($name, $val)
	{
		$this->conf[$name] = $val;
	}

	public function remove($name)
	{
		if (array_key_exists($name, $this->conf))
		{
			unset($this->conf[$name]);
			return true;
		}
		else
		{
			return false;
		}
	}

	public function toString()
	{
		$string = '';

		reset($this->conf);
		foreach ($this->conf as $key=>$val)
		{
			if (is_null($val))
				$val = 'null';
			else
				$val = str_replace("'", "\\'", $val);
			$string.=sprintf("\$%s['%s'] = '%s';\n", $this->conf_var_name, $key, $val);
		}
		return $string;
	}

	public function load()
	{
		if (@file_exists($this->conf_file))
		{
			include_once($this->conf_file);
			$this->conf =& ${$this->conf_var_name};
			return true;
		}
		else
		{
			throw new Exception("Unable to load config file: {$this->conf_file}");
			echo 'Config file does not exists.';
			exit();
			return false;
		}
	}

	public function save()
	{
		$string = file_get_contents($this->conf_file);
		$head = substr($string, 0, strpos($string, $this->begin_limiter)+strlen($this->begin_limiter));
		$foot = substr($string, strpos($string, $this->end_limter));
		unset($string);
		if (is_writable($this->conf_file))
		{
			@$fp = fopen($this->conf_file, 'w');
			@fwrite($fp, $head."\n".$this->toString().$foot);
			@fclose($fp);
			return true;
		}
		else
		{
			throw new Exception("Unable to write settings to config file");
			return false;
		}
	}
}

/* vim: set ts=4 sw=4 ff=unix: */
